<template>
  <div class="taxi-wait-content">
    <div class="top-car-region">
      <div class="driver-card-wraper border-bottom-1px">
        <div class="driver-card-content">
          <div class="driver-card-avatar">
            <img src="//taxife.didistatic.com/static/fe/default_driver_avator_v5.png">
          </div>
          <div class="driver-card-call">
            <a href="tel:138*****818" class="driver-card-phone">
              <div style="position: relative;left: 3px">
                <Icon name="phone" scale=1.2></Icon>
              </div>

            </a>
          </div>
          <div class="driver-card-info">
            <div class="driver-card-name-star-num">
              <span class="driver-card-name">杜师傅</span>
            </div>
            <div class="driver-card-licence-special">
              <div class="driver-card-licence">{{ carInfo.plateNumber }}</div>
            </div>
            <div class="driver-card-cartype">车辆： {{ carInfo.fullName }} ({{ carInfo.color }})</div>
          </div>
        </div>
      </div>
    </div>
<!--    <div class="amap">-->
<!--      <amap></amap>-->
<!--    </div>-->
    <div class="mf-bottom-bar">
      <div class="mf-bottombar-mod">

        <ul class="mf-bottombar-bd">
          <li data-index="0" @click="cancle_order">
            <button type="button" >
              <span>取消订单</span>
            </button>
          </li>
          <li data-index="1" >
            <button type="button" @click="web_error">
              <span>需要帮助</span>
            </button>
          </li>
          <li class="">
            <button type="">
              <div class="icon-ellipsis-h">
                <icon name="ellipsis-h"></icon>
              </div>
            </button>
          </li>
        </ul>
      </div>
    </div>
    <div id="container" style="height: 100%;width: 100%;background-color: #CCC"></div>
  </div>
</template>
<script>
import Icon from 'vue-awesome/components/Icon'
import amap from '@/components/public/amap.vue'
import {mapActions} from "vuex"
import {checkCarInfo, checkOrderRedis} from "../../api";
export default {
  data() {
    return {
      webSocket: {},
      orderNumber: '',
      carInfo: {},
      driverPosition: {
        lng: '',
        lat: ''
      }
    }
  },
  created() {
    let _this = this
    this.orderNumber = this.$route.query.orderNumber
    this.webSocket = new WebSocket('wss://localhost:8813/orderSocket/' + _this.$store.state.userInfo.token);
    this.webSocket.onerror = function (event) {
      onError(event)
    };
    this.webSocket.onopen = function (event) {
      onOpen(event)
    };
    this.webSocket.onmessage = function (event) {
      onMessage(event)
    };
    function onMessage(event) {
      let msg = JSON.parse(event.data)
      if (msg && msg.ping && msg.ping != '') {

      } else {
        _this.driverPosition.lng = msg.msg.driverLng
        _this.driverPosition.lat = msg.msg.driverLat
        if (msg.msg.orderNumber === _this.$store.state.order.orderNumber) {
          console.log("跳转")
          _this.$router.push({path:'/passenger/startJourney'})
        }
      }
    }
    function onOpen(event) {
      console.log('Connection established')
    }
    function onError(event) {
      alert(event.data);
    }

    setTimeout(() => {
      _this.getCarInfo(_this.orderNumber)
    },1000)
    // setInterval(() => {
    //   let positionPackage = {
    //     passengerLng: _this.$store.state.passengerPosition.lng,
    //     passengerLat: _this.$store.state.passengerPosition.lat
    //   }
    //   _this.webSocket.send('{"to":"' + _this.$store.state.order.driverToken + '","msg":' + JSON.stringify(positionPackage) + '}');
    // }, 5000)
  },
  mounted() {
    let _this = this
    var map = new AMap.Map("container", {
      resizeEnable: true,
      zoom: 12
    });

    AMap.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：5s
        buttonPosition:'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 30),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showCircle: false,
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function(status,result){
        if(status=='complete'){
          onComplete(result)
        }else{
          onError(result)
        }
      });
    });

    //解析定位结果
    function onComplete(data) {
      _this.$store.state.passengerPosition.lat = data.position.lat
      _this.$store.state.passengerPosition.lng = data.position.lng
    }
    //解析定位错误信息
    function onError(data) {
      console.log("定位失败:" + data.message)
    }

    setInterval(() => {
      var drivingOption = {
        policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
      }

      // 构造路线导航类
      var driving = new AMap.Driving(drivingOption)

      // 根据起终点经纬度规划驾车导航路线
      driving.search(new AMap.LngLat(_this.driverPosition.lng.toString(), _this.driverPosition.lat.toString()), new AMap.LngLat(_this.$store.state.order.startLongitude, _this.$store.state.order.startLatitude), function(status, result) {
        // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === 'complete') {
          if (result.routes && result.routes.length) {
            // 绘制第一条路线，也可以按需求绘制其它几条路线
            drawRoute(result.routes[0])
            // console.log('绘制驾车路线完成')
          }
        } else {
          console.log('获取驾车数据失败：' + result)
        }
      });

      function drawRoute (route) {
        var path = parseRouteToPath(route)

        var startMarker = new AMap.Marker({
          position: path[0],
          icon: './static/driver.png',
          map: map
        })

        var endMarker = new AMap.Marker({
          position: path[path.length - 1],
          icon: './static/passenger.png',
          map: map
        })

        var routeLine = new AMap.Polyline({
          path: path,
          isOutline: true,
          outlineColor: '#ffeeee',
          borderWeight: 2,
          strokeWeight: 5,
          strokeColor: '#18a33e',
          lineJoin: 'round'
        })

        routeLine.setMap(map)

        // 调整视野达到最佳显示区域
        map.setFitView([ startMarker, endMarker, routeLine ])
      }

      // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
      // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
      function parseRouteToPath(route) {
        var path = []

        for (var i = 0, l = route.steps.length; i < l; i++) {
          var step = route.steps[i]

          for (var j = 0, n = step.path.length; j < n; j++) {
            path.push(step.path[j])
          }
        }
        return path
      }
    },3000)

  },
  destroyed() {
    this.webSocket.close()
  },
  methods: {
    cancle_order() {
      this.$router.push({path:'/'})
    },
    web_error() {
      this.$router.push({path: '/webError'})
    },
    getCarInfo(orderNumber) {
      let _this = this
      checkOrderRedis({
        params: {
          orderNumber: orderNumber
        }
      })
      .then(res => {
        _this.$store.state.order = res.result
        checkCarInfo({
          params: {
            carId: _this.$store.state.order.carId
          }
        })
          .then(res => {
            _this.carInfo = res.result
          })
      })
    }
  },
  components: {
    Icon,
    amap
  },
  watch: {
  }
}
</script>
<style scoped>
.taxi-wait-content {
  height: 100%;
}
button{
  outline: none;
}
.amap {
  height: 800px;
  margin-top: -102px;
}

.top-car-region {
  position: relative;
  top: 0;
  z-index: 999;
  margin: 10px 5% 0px;
  box-shadow: 0 2px 3px rgba(0, 0, 0, .12);
}

.driver-card-wraper {

  /*border: 1px solid #000;*/
  border-radius: 2px;
  background-color: #fff;
  line-height: 1;
}

.driver-card-content {
  padding: 16px;
  height: 60px;
}

.driver-card-avatar {
  position: relative;
  float: left;
  width: 60px;
  height: 100%;
  margin-right: 10px;
  border-radius: 50%;
  background-color: #f9f9f9;
}

.driver-card-avatar>img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.driver-card-call {
  height: 100%;
  float: right;
  line-height: 60px;
  font-size: 0;
}

.driver-card-call>a {
  position: relative;
  font-size: 20px;
  color: #666;
  text-decoration: none;
  display: inline-block;
  height: 36px;
  width: 36px;
  border: 1px solid rgba(0, 0, 0, .4);
  line-height: 32px;
  vertical-align: middle;
  text-align: center;
  border-radius: 50%;
  margin-left: 12px;
}

.driver-card-call a>div {
  margin-top: 2px;
  margin-left: 5px;
}

.fa-icon {
  fill: rgba(0, 0, 0, .4);
}

.driver-card-info {
  text-align: left;
  font-size: 12px;
}

.driver-card-info>div {
  padding: 4px 0;
}

.driver-card-name {
  font-size: 16px;
  color: #333;
}

.mf-bottom-bar {
  position: absolute;
  z-index: 999;
  top:110px;
  width: 100%;
}

.mf-bottombar-mod {
  margin: 0 auto;
  width: 90%;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  box-shadow: 0 2px 3px rgba(0, 0, 0, .12);
}

.mf-bottombar-bd {
  background: #fff;
  display: flex;
  justify-content: space-around;
}
.mf-bottombar-bd li{
  display: inline-block;
  padding: 0 20px;
}
.mf-bottombar-bd li button {
  background: #fff;
  border: none;
}

.mf-bottombar-bd li button>span {
  display: inline-block;
  padding: 10px 0;
}
.mf-bottombar-bd li button .icon-ellipsis-h{
  margin-top: 10px;
}
</style>
